#!/usr/bin/env python
# encoding: utf-8
# @author: Lin Han
# @contact: voldemort22@126.com
# @file: migrate_clamp_database.py
# @time: 2021/3/30 19:20
# @desc:
import os

import pymongo

from .views.configs import *
from .utils.md5_tools import getFileMd5
from .utils.oss.oss import upload_file_to_oss
from .utils.utils import read_json

clamp_root_path = r"data/history_clamp"

original_clamp = read_json(r"D:\workspace\data_platform\script\original_clamp.json")

for i in original_clamp:
    i.pop("_id")

oss_file_dirname = "DOCenter_Dev/Pythonfiles/new_data/data/history_clamp"

new_clamp_list = []
# i就是每个夹具的文件夹一级了，i里面包含一个工件对应所有夹具，必须判断一下名字和后缀名。
total_number = 2021011000000000
for i in os.listdir(clamp_root_path):
    clamp_folder_path = f"{clamp_root_path}/{i}"
    print(f"clamp_folder_path: {clamp_folder_path}")
    # j就是每个夹具和工件的文件了
    for j in os.listdir(clamp_folder_path):
        total_number += 1

        print(j)
        # 没有上传工件的问题出在这里！下面的逻辑只会筛出名称最后一个字母为S的夹具，而忽略了工件（工件的名称是Work）
        if j.split(".")[-1] == "CATPart" and j.split(".")[0].endswith("S"):
            local_file_name = f"{clamp_folder_path}/{j}"

            temp_dict = {
                "number": str(total_number),
                "name": j,
                "desc": "历史夹具",
                "isFeature": False,
                "isFlag": False,
                "version": "1.0",
                "type": "1",
                "time": "2021-01-01 00:00",
                "tag": {
                    "standard": [],
                    "area": "",
                    "rpsNumber": "",
                    "airNumber": "",
                    "hasPin": False,
                    "hasStopBlock": False,
                    "rpsType": {},
                    "pinType": "",
                    "elseTag": []
                },
                "file": {
                    "catpartMd5": getFileMd5(local_file_name),
                    CATPART_OSS_ADDRESS: f"{oss_file_dirname}/{i}/{j}",
                },
            }

            upload_file_to_oss(local_file_name=local_file_name, oss_file_dirname=oss_file_dirname)

            print(temp_dict)

            for k in original_clamp:
                if temp_dict["file"]["catpartMd5"] == k["CGuid"]:
                    temp_dict["number"] = k["Number"]
                    temp_dict["isFeature"] = k["IsFeature"]
                    temp_dict["isFlag"] = True
                    temp_dict["name"] = k["Name"]
                    temp_dict["time"] = k["Time"]
                    temp_dict["tag"] = {}
                    temp_dict["tag"]["standard"] = [k["Tag"]["Standard"]]
                    temp_dict["tag"]["area"] = k["Tag"]["Area"]
                    temp_dict["tag"]["rpsNumber"] = k["Tag"]["RpsNumber"]
                    temp_dict["tag"]["airNumber"] = k["Tag"]["AirNumber"]
                    temp_dict["tag"]["hasPin"] = k["Tag"]["HasPin"]
                    temp_dict["tag"]["hasStopBlock"] = k["Tag"]["HasStopBlock"]
                    temp_dict["tag"]["pinType"] = k["Tag"]["PinType"]
                    temp_dict["tag"]["rpsType"] = k["Tag"]["RpsType"]
                    temp_dict["tag"]["elseTag"] = k["Tag"]["ElseTag"]
                    temp_dict["file"]["transferFormatMessage"] = "not transfered yet"
                    workpiece_file_path = f"{clamp_folder_path}/Work.CATPart"
                    temp_dict["file"]["workpieceCatpartMd5"] = getFileMd5(workpiece_file_path)
                    temp_dict["file"][WORKPIECE_CATPART_OSS_ADDRESS] = f"{oss_file_dirname}/{i}/Work.CATPart"
                    upload_file_to_oss(local_file_name=workpiece_file_path, oss_file_dirname=oss_file_dirname)

            new_clamp_list.append(temp_dict)

# for i in new_clamp_list:
#     i.pop("_id")

myclient = pymongo.MongoClient(MONGO_URL)
mydb = myclient["do_center"]
clamp = mydb["history_clamp"]
clamp.insert_many(new_clamp_list)
